package tk.winshu.shortestpath.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import tk.winshu.shortestpath.model.Node;
import tk.winshu.shortestpath.model.NodeData;

import java.util.List;

import static tk.winshu.shortestpath.util.ImportUtil.*;

/**
 * 导出工具类
 *
 * @author winshu
 * @date 2015年2月7日
 */
public class ExportUtil {

    /**
     * 导出
     */
    public static void exportTo(NodeData data, String path) {
        JSONObject object = new JSONObject();
        object.put(NODES_TAG, buildNodes(data.getNodes()));
        object.put(LINES_TAG, buildLines(data.getNodes()));
        object.put(SOURCE_TAG, data.getStartIndex());
        object.put(TARGET_TAG, data.getEndIndex());

        FileUtil.saveTo(path, object.toJSONString());
    }

    /**
     * 连线信息
     */
    private static JSONArray buildLines(List<Node> nodes) {
        JSONArray data = new JSONArray();
        for (Node start : nodes) {
            for (Node end : start.getEndNodes()) {
                JSONObject object = new JSONObject();
                object.put(START_TAG, start.getIndex());
                object.put(END_TAG, end.getIndex());
                data.add(object);
            }
        }
        return data;
    }

    /**
     * 节点信息
     */
    private static JSONArray buildNodes(List<Node> nodes) {
        JSONArray data = new JSONArray();
        for (Node node : nodes) {
            JSONObject object = new JSONObject();
            object.put(INDEX_TAG, node.getIndex());
            object.put(LOCATION_TAG, node.getLocation());
            data.add(object);
        }
        return data;
    }

}
